package com.spica.spicaschool.ui.diarysee

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
import androidx.lifecycle.rxLifeScope
import com.kongzue.dialogx.dialogs.TipDialog
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.bean.diarysee.DiaryInfo
import com.spica.spicaschool.databinding.FragmentDiarySeeBinding
import com.spica.spicaschool.network.Url
import com.spica.spicaschool.utils.AndroidBug5497Workaround
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import com.spica.spicaschool.utils.UiUtils
import rxhttp.wrapper.param.RxHttp
import timber.log.Timber
import java.net.URLDecoder

/**
 * 日记详情
 */

@Suppress("unused")
class DiarySeeFragment : BaseFragment<FragmentDiarySeeBinding>() {

    private var diaryId = ""

    @SuppressLint("SetJavaScriptEnabled")
    private fun initView() {
        AndroidBug5497Workaround.assistActivity(requireActivity())
        viewBinding.holderView.showWait()
        // 允许支持Js
        diaryId = arguments?.getString("DiaryId") ?: ""

        viewBinding.webview.settings.javaScriptEnabled = true
        viewBinding.webview.webViewClient = NewWebClient()
        viewBinding.viewpager.adapter =
            DiarySeePagerAdapter(
                childFragmentManager,
                BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
                diaryId
            )
        // 导航栏
        viewBinding.layoutTab.setupWithViewPager(viewBinding.viewpager)
        viewBinding.btnPush.setOnClickListener {
            reply()
        }
    }

    @Suppress("DEPRECATION")
    @SuppressLint("SetTextI18n")
    private fun initData() {
        // 获取数据
        rxLifeScope.launch(
            {
                RxHttp.postForm(Url.DIARY_INFO)
                    .add(
                        "token",
                        SpUtils.getSpValue(
                            context = requireContext(),
                            key = TOKEN_SIGN,
                            defaultVal = ""
                        )
                    )
                    .add("did", diaryId)
                    .asResponseList(DiaryInfo::class.java)
                    .subscribe {
                        requireView().post {
                            val data = it[0]
                            with(viewBinding, {
                                tvAuthorName.text = data.user.uNickname
                                tvAuthorInfo.text = "${data.user.uRank}级 萌新"
                                tvDiaryDesc.text =
                                    "${data.diaryReadNum}次浏览 · ${data.diaryLikeNum}次赞同"
                                tvTitle.text = data.diaryTitle
                                webview.loadDataWithBaseURL(
                                    null,
                                    URLDecoder.decode(data.diaryContent),
                                    "text/html",
                                    "utf-8",
                                    null
                                )
                                tvTime.text = data.diaryTime
                            })
                        }
                    }
            },
            {
                Toast.makeText(requireContext(), it.message, Toast.LENGTH_LONG).show()
            }
        )
    }



    // 评论
    private fun reply() {
        if (viewBinding.etComment.text.isNullOrEmpty()) {
            Toast.makeText(requireContext(), "写点啥吧！", Toast.LENGTH_SHORT).show()
        } else {
            RxHttp.postForm(Url.ADD_COMMMENT)
                .add("token", SpUtils.getSpValue(defaultVal = "", key = TOKEN_SIGN, context = requireContext()))
                .add("did", diaryId)
                .add("content", viewBinding.etComment.text.toString())
                .asOkResponse()
                .subscribe({
                    if (it.code == 200) {
                        Timber.e("message: ${it.message}")
                    }
                }, {
                    TipDialog.show(it.message)
                })

        }
    }


    inner class NewWebClient : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            UiUtils.doMainThreadle({
                viewBinding.holderView.showSuccess()
                viewBinding.containerView.visibility = View.VISIBLE
            }, 300)
        }
    }

    override fun setupViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentDiarySeeBinding = FragmentDiarySeeBinding.inflate(layoutInflater, container, false)

    override fun init() {
        initView()
        initData()
    }


}
